import {ref} from 'vue'
import {defineStore} from 'pinia'
import router from "@/router/index.js";

const modules = import.meta.glob("../views/**")
const resolveComponent = (path) => {
    return modules[`../views/${path}`]
}

export const useMenuStore = defineStore('menu', () => {
    const menuList = ref([])
    const btnList = ref([])

    function setMenuList(menus) {
        menuList.value = menus
        const buttons = []
        getButtons(buttons, menus)
        // console.log('buttons', buttons)
        btnList.value = buttons.map(item => item.code)
        // console.log('buttons', btnList.value)

        // 动态添加路由
        addRoute(menuList.value);
        console.log(router.getRoutes())
    }

    return {menuList, btnList, setMenuList}
})


const addRoute = (menus) => {
    for (let i = 0; i < menus.length; i++) {
        const t = menus[i]
        if (t.type === 'menu' && t.path && t.component) {
            // 添加路由
            router.addRoute('Layout', {
                path: t.path,
                meta: {
                    title: `${t.name}`
                },
                component: resolveComponent(t.component)
            })
        }
        if (t.children && t.children.length > 0) {
            addRoute(t.children)
        }
    }


}

const getButtons = (buttons, menus) => {
    for (let i = 0; i < menus.length; i++) {
        const t = menus[i]
        if (t.type === 'button') {
            buttons.push(t)
        }
        if (t.children && t.children.length > 0) {
            getButtons(buttons, t.children)
        }
    }
}
